﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitOfWorkCore.Infrastructure.Context
{
    /// <summary>
    /// 数据库链接服务
    /// </summary>
    public static class DbContextSetup
    {
        /// <summary>
        /// 注入数据库服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static IServiceCollection AddUseContext(this IServiceCollection services)
        {
            var config = services.BuildServiceProvider().GetRequiredService<IConfiguration>();
            var dbObject = config.GetSection("Db").GetChildren()
                .FirstOrDefault(c => bool.TryParse(c["Enabled"], out var enabled) && enabled);

            string dbType = dbObject?.Key ?? "MySql"; // 默认使用 MySql  
            string dbConn = dbObject?["dbconn"]
                            ?? throw new InvalidOperationException("Unable to find a valid database connection string");

            return services.AddDomainContext(builder =>
            {
                _ = dbType switch
                {
                    "SqlServer" => builder.UseSqlServer(dbConn),
                    "Oracle" => builder.UseOracle(dbConn),
                    "PostgreSql" => builder.UseNpgsql(dbConn),
                    "Sqlite" => builder.UseSqlite(dbConn),
                    _ => builder.UseMySql(dbConn, ServerVersion.AutoDetect(dbConn)) // 默认情况  
                };
            });
        }

        /// <summary>
        /// 将 AppDbContext 注册到依赖注入容器中
        /// </summary>
        /// <param name="services"></param>
        /// <param name="optionsAction"></param>
        /// <returns></returns>
        public static IServiceCollection AddDomainContext(this IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction)
        {
            // 调用 AddDbContext 方法，将 AppDbContext 注册到依赖注入容器
            return services.AddDbContext<AppDbContext>(optionsAction);
        }
    }
}
